package gemeente.meldStad;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.content.Context;
import android.util.Log;


//Klasse welke de data-afhandeling met betrekking tot XML parsers regelt.
public class Data {
	//statics meldingen moeten overal beschikbaar zijn
	public static List<Melding> meldingen;
	//URL meldingen GEOSERVER
	private static String URLMELDINGEN = "http://fleximap.groningen.nl/geoserver/wfs?service=WFS&REQUEST=GetFeature&outputformat=GML2&TYPENAME=gnmaps:WFS_MELDINGEN";
	private static String URLDETAILMELDING = "http://fleximap.groningen.nl/geoserver/wfs?service=WFS&REQUEST=GetFeature&outputformat=GML2&TYPENAME=gnmaps:MOR_MELDINGEN&srsName=EPSG:4326";
	//xml formated id filter &&id&& replacement voor id
	private static String URLIDFILTER = "&Filter=%3CFilter%3E%3CPropertyIsEqualTo%3E%3CPropertyName%3EMELD_NR%3C/PropertyName%3E%3CLiteral%3E&&id&&%3C/Literal%3E%3C/PropertyIsEqualTo%3E%3C/Filter%3E";
	//huidige gebruiker
    public static Gebruiker gebruiker;
	//boolean debugmode
    public static boolean DEBUG = true;
    
    //klasse getMeldingen()
    //
    //Haal alle meldingen op en vul de statische lijst met meldingen
    // return: list<Meldingen> || null
	public static List<Melding> getMeldingen() throws XmlPullParserException, IOException
	  {
			//init xmlparser
			meldingen= new ArrayList<Melding>();	
		   XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		   factory.setNamespaceAware(false);
		   XmlPullParser xpp = factory.newPullParser();
	
		   //url request XML met alle meldingen
		   URL url = new URL(URLMELDINGEN);
		   URLConnection ucon = url.openConnection();
		   InputStream is = ucon.getInputStream();
		   
		   //buffered reader om de XML in te lezen
		   BufferedReader rd = new BufferedReader(new InputStreamReader(is));
		   xpp.setInput(rd);
		   int eventType = xpp.getEventType();
		   Melding curr = new Melding();
		   
		   //voor elk element in het document 
		   while (eventType != XmlPullParser.END_DOCUMENT)
		   {	  
			   //filter de tags eruit en plaats de inhoud bij
			   //bijhorend element van het melding object 
			    if(eventType == XmlPullParser.START_TAG)
			    {
			    	if(xpp.getName().equals("gml:featureMember")){
			    		curr = new Melding();
			    	}else if(xpp.getName().equals("gnmaps:WFS_ID")){
			    		xpp.next();
			    		curr.setId(Integer.valueOf(xpp.getText()));
			    	}else if(xpp.getName().equals("gnmaps:DESCRIPTION")){
			    		xpp.next();
			    		curr.setDescription(xpp.getText());
			    	}else if(xpp.getName().equals("gnmaps:STATUS")){
			    		xpp.next();
			    		curr.setStatus(xpp.getText());
			    	}
			    	else if(xpp.getName().equals("gml:coordinates")){
			    		xpp.next();
			    		curr.setRdY(Double.valueOf(xpp.getText().split(",")[0]).doubleValue());
			    		curr.setRdX(Double.valueOf(xpp.getText().split(",")[1]).doubleValue());
			    		
			    		String lola[] = Data.RDTolonglat(curr.getRdY(), curr.getRdX());
			    		curr.setLongitude(Double.valueOf(lola[1]));
			    		curr.setLatitude(Double.valueOf(lola[0]));
			
			    	}
			    //Als aflsuitende melding tag, toevoegen aan de statische melding lijst
			    }else if(eventType == XmlPullParser.END_TAG){
			    	if(xpp.getName().equals("gml:featureMember")){
			    		meldingen.add(curr);
			    	}
			    }
			    eventType = xpp.next();
		   }
	   return meldingen;
	  }
	
	//getDetailMelding()
	// - id: id van de te zoeken meldingdetails
	// - melding: Melding welke aangevult moet worden met detail
	//
	// Op basis van uniek melding id een url request doen  
	//return melding || null
	public static Melding getDetailMelding(Melding curr) throws Exception{
		//init cxmlparser
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		   factory.setNamespaceAware(false);
		   XmlPullParser xpp = factory.newPullParser();
		   
		   //init URLrequest
		   URL url = new URL(URLDETAILMELDING + URLIDFILTER.replace("&&id&&", ""+curr.getId()) );
		   URLConnection ucon = url.openConnection();
		   InputStream is = ucon.getInputStream();
		  
		   //BufferedInputStream buf = new BufferedInputStream(is);
		   BufferedReader rd = new BufferedReader(new InputStreamReader(is));
		   xpp.setInput(rd); 
		   int eventType = xpp.getEventType();

		   while (eventType != XmlPullParser.END_DOCUMENT)
		   {	  
			   //filter xmltags en plaat de inhoud bij bijhored meldingatribuut
			    if(eventType == XmlPullParser.START_TAG)
			    {
			    	if(xpp.getName().equals("gml:featureMember")){
			    	}else if(xpp.getName().equals("gnmaps:ADRES")){
			    		xpp.next();			  
			    		if(xpp.getText().contains(",")){
				    		curr.setStraat(xpp.getText().split(",")[0]);
				    		curr.setPlaats(xpp.getText().split(", ")[1].trim());
			    		}else{
			    			curr.setStraat(xpp.getText());
			    		}
			    	}else if(xpp.getName().equals("gnmaps:CATEGORIE")){
			    		xpp.next();
			    		curr.setCategory(xpp.getText());
			    	}else if(xpp.getName().equals("gnmaps:OMSCHRIJVING")){
			    		xpp.next();
			    		curr.setDescription(xpp.getText());
			    	}else if(xpp.getName().equals("gnmaps:BIJZONDERHEDEN")){
			    		xpp.next();
			    		curr.setBijzonderheden(xpp.getText());
			    	}else if(xpp.getName().equals("gnmaps:GROEP")){
			    		xpp.next();
			    		curr.setGroep(xpp.getText());
			    	}else if(xpp.getName().equals("gnmaps:STATUS")){
			    		xpp.next();
			    		curr.setStatus(xpp.getText());
			    	}else if(xpp.getName().equals("gnmaps:TERMIJN")){
			    		xpp.next();
			    		curr.setOplossingtermijn(xpp.getText());
			    	}   	   	
			    }
			    eventType = xpp.next();
		   }	
		return curr;	
	}
	
	//getDetailMelding(l)
	// - rdx: double waarde met x co
	// - rdy: double waarde met y co
	//
	//In geval van eigen meldingen zoek detail op basis van RDx en RDy coordinaten
	//return Melding || null
	public static Melding getDetailMelding(double rdx, double rdy){
		Melding curr = null;
		Boolean hit=false;
		
		//Loop door bekende meldingen tot eigen melding is gevonden
		for(int i=0; i< meldingen.size();i++){
			if(rdx==meldingen.get(i).getRdY() && rdy== meldingen.get(i).getRdX()){
				try {
					curr = meldingen.get(i);
					hit=true;
					curr = getDetailMelding(curr);
					break;
				} catch (Exception e) {
					if(DEBUG){Log.e("ERROR:" ,e.getMessage());}
				}
			}

		}	
		return curr;	
	}
	
	//SaveMeldingLokaal()
	// - Context: Context van huidige activity
	// - melding: De melding met de data op te slaan
	//
	//Sla een gemaakte melding lokaal op voor latere referentie in het mijnMeldingen Activity
	//return void
	public static void saveMeldingLokaal(Context con, Melding melding){
		try {
		      DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
		      DocumentBuilder parser = fact.newDocumentBuilder();
	 
		      File xmlPath =  new File(con.getFilesDir() + "\\meldingen.xml");  
		      Document doc;
		      if(xmlPath.exists()){
		    	  doc = parser.parse(xmlPath);
		      }else{
		    	  doc = parser.newDocument();
		      }
		      
		      //hoofd node
		      NodeList firsth = doc.getChildNodes();
		      Node top = null;
		      
		      for(int i=0;i<firsth.getLength();i++){
		    	  if(firsth.item(i).getNodeName().equals("resources")){
		    		  top = firsth.item(i);		    		 
		    		  break;
		    	  }
		      }
		      	if(top == null){
		      		top = doc.createElement("resources");
		      		doc.appendChild(top);
		      	}
		      
		    	  Node nodemelding = doc.createElement("mijn_melding");
		    	  top.appendChild(nodemelding);
		    	  
		    	  
		    	  Node curr = doc.createElement("id");
		    	  nodemelding.appendChild(curr);
		    	  curr.appendChild(doc.createTextNode(""+melding.getId()));
		    	  
		    	  curr = doc.createElement("categorie");
		    	  nodemelding.appendChild(curr);
		    	  curr.appendChild(doc.createTextNode(""+melding.getCategory()));

		    	  curr = doc.createElement("longitude");
		    	  nodemelding.appendChild(curr);
		    	  curr.appendChild(doc.createTextNode(""+melding.getLongitude()));

		    	  curr = doc.createElement("latitude");
		    	  nodemelding.appendChild(curr);
		    	  curr.appendChild(doc.createTextNode("" + melding.getLatitude()));
		    	  
		    	  curr = doc.createElement("rdy");
		    	  nodemelding.appendChild(curr);
		    	  curr.appendChild(doc.createTextNode(""+melding.getRdY()));

		    	  curr = doc.createElement("rdx");
		    	  nodemelding.appendChild(curr);
		    	  curr.appendChild(doc.createTextNode("" + melding.getRdX()));
		    	  
		    	  curr = doc.createElement("date");
		    	  nodemelding.appendChild(curr);
		    	  curr.appendChild(doc.createTextNode(""+melding.getDate()));

		    	  curr = doc.createElement("description");
		    	  nodemelding.appendChild(curr);
		    	  curr.appendChild(doc.createTextNode(""+melding.getDescription()));

		    	  curr = doc.createElement("status");
		    	  nodemelding.appendChild(curr);
		    	  curr.appendChild(doc.createTextNode(""+melding.getStatus()));

		    	  curr = doc.createElement("picture");
		    	  nodemelding.appendChild(curr);
		    	  curr.appendChild(doc.createTextNode(""+melding.getPicture()));

		    	  curr = doc.createElement("straat");
		    	  nodemelding.appendChild(curr);
		    	  curr.appendChild(doc.createTextNode(""+melding.getStraat()));

		    	  curr = doc.createElement("plaats");
		    	  nodemelding.appendChild(curr);
		    	  curr.appendChild(doc.createTextNode(""+melding.getPlaats()));

		    	  //write XML to file
		    	  String toFile = getStringFromNode(doc);
		    	  Writer out = new OutputStreamWriter(new FileOutputStream(xmlPath));
		    	  
		    	  try {
		    	      out.write(toFile);
		    	  }finally {
		    	      out.close();
		    	  }
		    	  
		    } catch (Exception ex) {
		      if(DEBUG){Log.e("ERROR:","@saveMeldingLokaal()", ex);}
		    }
	}
	
	//getMeldingenLokaal()
	//Activity: hudiige activity voor context
	//
	//Context: voor referentie
	//return List<Melding> || null
	public static List<Melding> getMeldingenLokaal(Context con) throws XmlPullParserException, IOException
	  {
	   List<Melding> meldingen= new ArrayList<Melding>();
	   
	   //prep xmlparser en inputreaders van lokale file
		File xmlPath =  new File(con.getFilesDir() + "\\meldingen.xml");
		XmlPullParserFactory factory = XmlPullParserFactory.newInstance();  
		factory.setNamespaceAware(false);		
		XmlPullParser xpp = factory.newPullParser();
		InputStream is = new FileInputStream(xmlPath);  
	    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
	    int eventType = xpp.getEventType();
	    xpp.setInput(rd);
	   
	    Melding curr = new Melding();
	    while (eventType != XmlPullParser.END_DOCUMENT)
	    {	  
		    if(eventType == XmlPullParser.START_TAG)
		    {
		    	if(xpp.getName().equals("mijn_melding")){
		    		curr = new Melding();
		    	}else if(xpp.getName().equals("id")){
		    		xpp.next();
		    		curr.setId(Integer.valueOf(xpp.getText()));
		    	}else if(xpp.getName().equals("date")){
		    		xpp.next();
		    		curr.setDate((xpp.getText()));
		    	}else if(xpp.getName().equals("description")){
		    		xpp.next();
		    		curr.setDescription(xpp.getText());
		    	}else if(xpp.getName().equals("categorie")){
		    		xpp.next();
		    		curr.setCategory(xpp.getText());
		    	}else if(xpp.getName().equals("longitude")){
		    		xpp.next();
		    		curr.setLongitude(Double.valueOf(xpp.getText()).doubleValue());
		    	}else if(xpp.getName().equals("latitude")){
		    		xpp.next();
		    		curr.setLatitude(Double.valueOf(xpp.getText()).doubleValue());
		    	}else if(xpp.getName().equals("rdy")){
			    	xpp.next();
			    	curr.setRdY(Double.valueOf(xpp.getText()).doubleValue());
			    }else if(xpp.getName().equals("rdx")){
			    	xpp.next();
			    	curr.setRdX(Double.valueOf(xpp.getText()).doubleValue());
			    }else if(xpp.getName().equals("date")){
		    		xpp.next();
		    		curr.setDate(xpp.getText());
		    	}else if(xpp.getName().equals("status")){
		    		xpp.next();
		    		curr.setStatus(xpp.getText());
		    	}else if(xpp.getName().equals("straat")){
		    		xpp.next();
		    		curr.setStraat(xpp.getText());
		    	}else if(xpp.getName().equals("categorie")){
		    		xpp.next();
		    		curr.setCategory(xpp.getText());
		    	}else if(xpp.getName().equals("plaats")){
		    		xpp.next();
		    		curr.setPlaats(xpp.getText());
		    	}else if(xpp.getName().equals("postcode")){
		    		xpp.next();
		    		curr.setPostcode(xpp.getText());
		    	}else if(xpp.getName().equals("picture")){
		    		xpp.next();
		    		curr.setPicture(xpp.getText());
		    	}
		    }else if(eventType == XmlPullParser.END_TAG){
		    	if(xpp.getName().equals("mijn_melding")){
		    		meldingen.add(curr);
		    	}
		    }
		    eventType = xpp.next();
	   }
	    //omdraaien zodat nieuwe meldingen boven komen te staan
	    Collections.reverse(meldingen);	    
	    return meldingen; 
	  }
	

	//getStringFromNode()
	//-root: root element Dom object
	//
	//Android ondersteund het opslaan van een DOM xmlobject niet als java dat doet
	//work-around om deze in String terug tye halen om bv. op te slaan
	//return: String
	public static String getStringFromNode(Node root) throws IOException {

        StringBuilder result = new StringBuilder();

        if (root.getNodeType() == 3)
            result.append(root.getNodeValue());
        else {
            if (root.getNodeType() != 9) {
                StringBuffer attrs = new StringBuffer();
                for (int k = 0; k < root.getAttributes().getLength(); ++k) {
                    attrs.append(" ").append(
                            root.getAttributes().item(k).getNodeName()).append(
                            "=\"").append(
                            root.getAttributes().item(k).getNodeValue())
                            .append("\" ");
                }
                result.append("<").append(root.getNodeName()).append(" ")
                        .append(attrs).append(">");
            } else {
                result.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            }

            NodeList nodes = root.getChildNodes();
            for (int i = 0, j = nodes.getLength(); i < j; i++) {
                Node node = nodes.item(i);
                result.append(getStringFromNode(node));
            }

            if (root.getNodeType() != 9) {
                result.append("</").append(root.getNodeName()).append(">");
            }
        }
        return result.toString();
    }
	
	//gebruikerBestaat()
	// con: Context voor referentie
	//
	//controleert op basis van filepath of er al een gebruiker is aangemaakt
	//Zo ja lees deze gevens in en maak ze statisch beschikbaar in de app als Gebruiker object
	//
	//return: true || false
	public static boolean gebruikerBestaat(Context con) throws XmlPullParserException, IOException{
		File xmlPath =  new File(con.getFilesDir() + "\\gebruiker.xml");
		if(xmlPath.exists()){
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();  
			factory.setNamespaceAware(false);			
			XmlPullParser xpp = factory.newPullParser();
			InputStream is = new FileInputStream(xmlPath);

		   BufferedReader rd = new BufferedReader(new InputStreamReader(is));			   
		   int eventType = xpp.getEventType();
		   xpp.setInput(rd);			   
		   Gebruiker geb = new Gebruiker();
		   while (eventType != XmlPullParser.END_DOCUMENT)
		   {	  
			    if(eventType == XmlPullParser.START_TAG)
			    {
			    	if(xpp.getName().equals("naam")){
			    		xpp.next();
			    		geb.setNaam(xpp.getText());
			    	}else if(xpp.getName().equals("mail")){
			    		xpp.next();
			    		geb.setMail(xpp.getText());
			    	}else if(xpp.getName().equals("postcode")){
			    		xpp.next();
			    		geb.setPostcode(xpp.getText());
			    	}else if(xpp.getName().equals("huisnummer")){
			    		xpp.next();
			    		geb.setHuisnummer(xpp.getText());
			    	}else if(xpp.getName().equals("telefoon")){
			    		xpp.next();
			    		geb.setTelefoon(xpp.getText());
			    	}else if(xpp.getName().equals("anoniem")){
			    		xpp.next();
			    		if(xpp.getText().equals("true")){
			    			geb.setAnoniem(true);
			    		}else{
			    			geb.setAnoniem(false);
			    		}
			    	}
			    }else if(eventType == XmlPullParser.END_TAG){
			    	if(xpp.getName().equals("gebruiker")){
			    		gebruiker = geb;
			    	}
			    }
			    eventType = xpp.next();
		   }	
			return true;
		}else{
			return false;
		}
	}
	
	// saveGebruiker()
	// - con: referentie
	// - geb: het op te slaan gebruiker instantie
	//
	//slaat gebruiksgegevens op onder pad: data/data/[package_name]/files/gebruiker.xml
	//uit lezen door gebruikerBestaat()
	public static void saveGebruiker(Context con, Gebruiker geb){
		try {
		      DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
		      DocumentBuilder parser = fact.newDocumentBuilder();
	 
		      File xmlPath =  new File(con.getFilesDir() + "\\gebruiker.xml");
		      Document doc = parser.newDocument();
		  
		      Node top = null;
		      
		      	 top = doc.createElement("gebruiker");
		      	 doc.appendChild(top);
 	  
		    	  Node curr = doc.createElement("naam");
		    	  top.appendChild(curr);
		    	  curr.appendChild(doc.createTextNode(""+geb.getNaam()));
		    	  
		    	  curr = doc.createElement("mail");
		    	  top.appendChild(curr);
		    	  curr.appendChild(doc.createTextNode(""+geb.getMail()));

		    	  curr = doc.createElement("postcode");
		    	  top.appendChild(curr);
		    	  curr.appendChild(doc.createTextNode(""+geb.getPostcode()));

		    	  curr = doc.createElement("huisnummer");
		    	  top.appendChild(curr);
		    	  curr.appendChild(doc.createTextNode(""+geb.getHuisnummer()));
		    	  
		    	  curr = doc.createElement("telefoon");
		    	  top.appendChild(curr);
		    	  curr.appendChild(doc.createTextNode("" + geb.getTelefoon()));

		    	  curr = doc.createElement("anoniem");
		    	  top.appendChild(curr);
		    	  curr.appendChild(doc.createTextNode("" + geb.isAnoniem()));

		    	  //write XML to file
		    	  String toFile = getStringFromNode(doc);
		    	  Writer out = new OutputStreamWriter(new FileOutputStream(xmlPath));
		    	  
		    	  try {
		    	      out.write(toFile);
		    	  }finally {
		    	      out.close();
		    	  }
		    	  
		    } catch (Exception ex) {
		    	if(DEBUG){Log.e("ERROR:","@saveGbruiker", ex);}
		    }
	}
	
	//op basis van longitude en latitude een lokale melding verwijderen
	//uit het meldingen xml object
	
	public static void deleteLokaalMelding(Context con, Melding melding) throws Exception{
		DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
  		DocumentBuilder parser = fact.newDocumentBuilder();

  		File xmlPath =  new File(con.getFilesDir() + "\\meldingen.xml");  
  		Document doc;
  		if(xmlPath.exists()){
  			doc = parser.parse(xmlPath);
  		}else{
  			return;
  		}
  			
  		
  		NodeList meldingen = doc.getElementsByTagName("mijn_melding");
  		for(int i=0;i<meldingen.getLength();i++){
  			NodeList children = meldingen.item(i).getChildNodes();
  			boolean longhit = false;
  			boolean lathit = false;
  			for(int j=0;j<children.getLength();j++){
  				if(children.item(j).getNodeName().equals("longitude")){
  		
  	  				
  					if(Double.valueOf(children.item(j).getLastChild().getNodeValue()).doubleValue()==(melding.getLongitude()))
  					{
  						longhit=true;
  					}
  				}else if(children.item(j).getNodeName().equals("latitude")){
  					if(Double.valueOf(children.item(j).getLastChild().getNodeValue()).doubleValue()==(melding.getLatitude())){
						lathit=true;
					}
  				}
  			}
  			//zijn long en lat hetzelfde dan verwijderen.
  			if(longhit&&lathit){
  				meldingen.item(i).getParentNode().removeChild(meldingen.item(i));
  	 			//en nieuwe xml opslaan
  	  			//write XML to file
  		    	  String toFile = getStringFromNode(doc);
  		    	  Writer out = new OutputStreamWriter(new FileOutputStream(xmlPath));
  		    	  
  		    	  try {
  		    	      out.write(toFile);
  		    	  }finally {
  		    	      out.close();
  		    	  }
  		    	  //evt plaatje verwijderen
  		    	  File URL = new File(con.getFilesDir() + "//" +  melding.getPicture());
  		    	  if(URL.exists())
  		    	  {
  		    		  URL.delete();
  		    	  }
  		    	  break;
  			}	
  		} 
	}
	
	//implementatie voor lezen post request
	public static List<String> getPic(String meldNr)throws XmlPullParserException, IOException{
		try {
			
			String requestraw =  "<?xml version='1.0' encoding='UTF-8' standalone='no'?>" +
        	"<FMGetInfo version='2.1.0' xmlns='http://www.bentley.com/FlexiMap' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://www.bentley.com/FlexiMap FMRequest.xsd'>" +
        	"<Service>gnmaps</Service>"+
        	"<KeyInfo>"+
        	"<Keys layer='meldingen' keys='"+ meldNr +"' />"+
        	"</KeyInfo>"+
        	"<MapLayers>meldingen</MapLayers>"+
        	"<MapResolution>0.5</MapResolution>"+
        	"<MapWidth>600</MapWidth>"+
        	"<MapHeight>500</MapHeight>"+
        	"</FMGetInfo>";
			
			HttpClient client = new DefaultHttpClient();  
			HttpPost httppost = new HttpPost("http://fleximap.groningen.nl/scripts/Fleximap.dll");          
			StringEntity se = new StringEntity(requestraw,HTTP.UTF_8);

			se.setContentType("text/xml");  
			httppost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");

			httppost.setEntity(se);  	
			HttpResponse responsePOST = client.execute(httppost);
			HttpEntity resEntity = responsePOST.getEntity();  
           // Header extra = responsePOST.getFirstHeader("Records");
            String xml = EntityUtils.toString(resEntity);
			if (xml != null) {    				
				return parsePicXML(xml, meldNr);
            }
								
			//return URL;
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return null;
	}
	
	public static List<String> parsePicXML(String xml, String meldNr) throws XmlPullParserException, IOException
	  {
		List<String> urls =new ArrayList<String>();
		
		//init cxmlparser
		XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		factory.setNamespaceAware(false);
		XmlPullParser xpp = factory.newPullParser();

		InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
		
		//BufferedInputStream buf = new BufferedInputStream(is);
		BufferedReader rd = new BufferedReader(new InputStreamReader(is));
		xpp.setInput(rd); 
		int eventType = xpp.getEventType();
		
		int record = 0;
		int item = 0;
		String dir = null;
		String filename = null;
		
		while (eventType != XmlPullParser.END_DOCUMENT)
	    {	  
		    if(eventType == XmlPullParser.START_TAG)
		    {
		    	if(xpp.getName().equals("Record")){		    		
		    	}else if(xpp.getName().equals("Item")){
		    		xpp.next();
		    		if(meldNr.equals(xpp.getText())){
		    			//eerste record bevat geen nodige informatie voor de plaatjes
		    			if(record != 0){
		    				item++;
		    			}
		    			record++;
		    		//item 1 bevat de directory nummer
		    		}else if(item == 1){
		    			dir = xpp.getText();
		    			item++;
		    		//item 2 bevat de filenaam
		    		}else if(item == 2){
		    			filename = xpp.getText();	    			
		    			urls.add("http://fleximap.groningen.nl/documenten/meldingen/" + dir + "_" + filename.replace("jpg", "JPG"));
		    			item = 0;
		    		}
		    		
		    	}
		    }
		    eventType = xpp.next();
	   }
						
        return urls;
	  }
	
	public static String[] longlatToRD(double lng, double lat){
		double dF = 0.36 * (lat - 52.15517440);
		double dL = 0.36 * (lng - 5.38720621);

		double SomX= (190094.945 * dL) + (-11832.228 * dF * dL) + (-144.221 * dF*dF * dL) + (-32.391 * dL*dL*dL) + (-0.705 * dF) + (-2.340 * dF*dF*dF * dL) + (-0.608 * dF * dL*dL*dL) + (-0.008 * dL*dL) + (0.148 * dF*dF * dL*dL*dL);
		double SomY = (309056.544 * dF) + (3638.893 * dL*dL) + (73.077 * dF*dF ) + (-157.984 * dF * dL*dL) + (59.788 * dF*dF*dF ) + (0.433 * dL) + (-6.439 * dF*dF * dL*dL) + (-0.032 * dF * dL) + (0.092 * dL*dL*dL*dL) + (-0.054 * dF * dL*dL*dL*dL);	
		
		double X = 155000 + SomX;
		double Y = 463000 + SomY;
		
		String[] XY  = new String[2];         
        XY[0] = Double.toString(X); // initialize first element
        XY[1] = Double.toString(Y); // initialize second element
		
		return XY;
	}
	
	public static String[] RDTolonglat(double xc, double yc){
	
		    double dX = (xc - 155000) * 1.0e-5;
		    double dY = (yc - 463000) * 1.0e-5;

		    double dN = (3235.65389 * dY) + (-32.58297 * Math.pow(dX,2)) + (-0.2475 * Math.pow(dY,2)) + (-0.84978 * Math.pow(dX,2) * dY) 
		       + (-0.0655 * Math.pow(dY,3)) + (-0.01709 * Math.pow(dX,2) * Math.pow(dY,2)) + (-0.00738 * dX) + (0.0053 * Math.pow(dX,4)) 
		       + (-0.00039 * Math.pow(dX,2) * Math.pow(dY,3)) + (0.00033 * Math.pow(dX,4) * dY) + (-0.00012 * dX * dY);
		    double dE = (5260.52916 * dX) + (105.94684 * dX * dY) + (2.45656 * dX * Math.pow(dY,2)) + (-0.81885 * Math.pow(dX,3)) 
		       + (0.05594 * dX * Math.pow(dY,3)) + (-0.05607 * Math.pow(dX,3) * dY) + (0.01199 * dY) + (-0.00256 * Math.pow(dX,3) * Math.pow(dY,2)) 
		       + (0.00128 * dX * Math.pow(dY,4)) + (0.00022 * Math.pow(dY,2)) + (-0.00022 * Math.pow(dX,2)) + (0.00026 * Math.pow(dX,5));

		    double Latitude = 52.15517 + (dN / 3600);
		    double Longitude = 5.387206 + (dE / 3600);
		    return new String[]{Latitude+"",Longitude+""};
	}
	
	

}